package com.example.demo.application

import android.app.Application
import com.example.demo.dao.AppDatabase
import com.example.demo.bean.User
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import timber.log.Timber

class MyApplication : Application() {
    val database by lazy { AppDatabase.getDatabase(this) }
    private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

    companion object {
        lateinit var instance: MyApplication
            private set
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        Timber.plant(Timber.DebugTree())
        applicationScope.launch {
            try {
                val userDao = database.userDao()
                val list = userDao.getAllUsers()
                if (list.isEmpty()) {
                    userDao.insert(User(name = "lei", pwd = "123456"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onTerminate() {
        super.onTerminate()
        applicationScope.cancel()
    }

}